<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>幸运抽奖</title>
    <style>
        /* 添加参与者管理按钮和表单的样式 */
        .participant-management {
            display: flex;
            justify-content: center;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }
        /* 改为弹框样式 - 核心修改1：弹框布局 */
        .participant-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .participant-modal.active {
            opacity: 1;
            visibility: visible;
        }
        .modal-content {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            max-width: 550px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            transform: translateY(-20px);
            transition: transform 0.3s ease;
        }
        .participant-modal.active .modal-content {
            transform: translateY(0);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 0.8rem;
            border-bottom: 1px solid #eee;
        }
        .modal-title {
            font-size: 1.5rem;
            color: #333;
            font-weight: bold;
            margin: 0;
        }
        .close-modal {
            background: none;
            border: none;
            font-size: 1.8rem;
            color: #666;
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        .close-modal:hover {
            background: #f5f5f5;
            color: #333;
        }
        /* 图片上传预览样式 - 核心修改2：上传预览区 */
        .upload-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin: 1rem 0;
            padding: 1rem;
            border: 2px dashed #ddd;
            border-radius: 5px;
            min-height: 100px;
        }
        .preview-item {
            position: relative;
            width: 80px;
            height: 80px;
            border-radius: 5px;
            overflow: hidden;
            border: 1px solid #eee;
        }
        .preview-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .remove-img {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ff4444;
            color: white;
            border: none;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 0.8rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            transition: background 0.3s;
        }
        .remove-img:hover {
            background: #cc0000;
        }
        .upload-hint {
            color: #666;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        .form-group {
            margin-bottom: 1.2rem;
        }
        .form-group label {
            display: block;
            color: #333;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        .form-control {
            width: 100%;
            padding: 0.8rem;
            border-radius: 5px;
            border: 1px solid #ddd;
            font-size: 1rem;
            transition: border 0.3s;
        }
        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }
        .form-actions {
            display: flex;
            gap: 1rem;
            margin-top: 1.8rem;
        }
        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(229, 57, 53, 0.8);
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 20;
            font-size: 1.2rem;
            transition: background 0.3s;
        }
        .delete-btn:hover {
            background: #e53935;
        }
        .manage-btn {
            background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
            color: white;
            border: none;
            padding: 0.6rem 1.5rem;
            font-size: 1rem;
            border-radius: 50px;
            cursor: pointer;
            margin: 0.5rem 0;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .manage-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
        }
        /* 其他原有样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 2rem;
            position: relative;
        }
        .header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .header h1 {
            font-size: 2.5rem;
            color: #333;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 0.5rem;
        }
        .header p {
            color: #666;
            font-size: 1.1rem;
        }
        .participants-toggle {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 0.8rem 2rem;
            font-size: 1.2rem;
            border-radius: 50px;
            cursor: pointer;
            margin: 1rem 0;
            box-shadow: 0 4px 15px rgba(118, 75, 162, 0.3);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .participants-toggle:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(118, 75, 162, 0.4);
        }
        /* 蒙版样式 */
        .participants-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            overflow-y: auto;
            padding: 2rem;
        }
        .participants-overlay.active {
            opacity: 1;
            visibility: visible;
        }
        .participants-overlay-header {
            color: white;
            margin-bottom: 2rem;
            text-align: center;
            width: 100%;
        }
        .participants-overlay-header h2 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }
        .close-participants {
            position: absolute;
            top: 20px;
            right: 20px;
            background: none;
            border: none;
            color: white;
            font-size: 2.5rem;
            cursor: pointer;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background 0.3s;
        }
        .close-participants:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        .participants-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 1.5rem;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }
        .participant-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            transition: transform 0.3s, box-shadow 0.3s;
            position: relative;
            cursor: pointer; /* 新增：指示可点击 */
        }
        .participant-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }
        .participant-imgs-container {
            position: relative;
            height: 180px;
            overflow: hidden;
            border-radius: 10px 10px 0 0;
        }
        /* 轮播修复1：设置轮播容器宽度为100%，确保图片完全适配 */
        .participant-imgs, .winner-imgs {
            display: flex;
            height: 100%;
            width: 100%;
            transition: transform 0.5s ease;
        }
        .participant-img, .winner-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            flex-shrink: 0;
        }
        .participant-name {
            padding: 1rem;
            text-align: center;
            font-weight: bold;
            color: #444;
        }
        .slider-dots {
            position: absolute;
            bottom: 10px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 5px;
        }
        .slider-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.5);
            cursor: pointer;
            transition: background 0.3s;
        }
        .slider-dot.active {
            background: white;
        }
        .draw-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 0.8rem 2rem;
            font-size: 1.2rem;
            border-radius: 50px;
            cursor: pointer;
            margin: 1rem 0;
            box-shadow: 0 4px 15px rgba(118, 75, 162, 0.3);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .draw-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(118, 75, 162, 0.4);
        }
        .draw-btn:active {
            transform: translateY(0);
        }
        .result-container {
            margin-top: 2rem;
            text-align: center;
            opacity: 0;
            transform: scale(0.9);
            transition: all 0.5s ease-out;
            width: 100%;
            max-width: 500px;
            padding: 1rem;
        }
        .result-container.show {
            opacity: 1;
            transform: scale(1);
        }
        .winner-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            padding: 2rem;
            display: inline-block;
            max-width: 300px;
            position: relative;
            overflow: hidden;
            width: 100%;
        }
        .winner-card::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }
        .winner-imgs-container {
            position: relative;
            width: 200px;
            height: 200px;
            margin: 0 auto 1rem;
            overflow: hidden;
            border-radius: 50%;
            border: 5px solid #f8f9fa;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        .winner-title {
            color: #764ba2;
            margin-bottom: 0.5rem;
            font-size: 1.8rem;
        }
        .winner-name {
            font-size: 1.8rem;
            color: #333;
            font-weight: bold;
            margin-top: 1rem;
        }
        .loading-indicator {
            color: white;
            font-size: 1.5rem;
            margin: 20px 0;
            display: none;
        }
        .empty-state {
            color: #aaa;
            font-size: 1.2rem;
            text-align: center;
            padding: 2rem;
            display: none;
        }
        .draw-animation {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .draw-animation.active {
            opacity: 1;
            visibility: visible;
        }
        .draw-spinner {
            width: 80px;
            height: 80px;
            border: 10px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 10px solid #764ba2;
            animation: spin 1s linear infinite;
        }
        .draw-message {
            color: white;
            font-size: 1.8rem;
            margin-top: 2rem;
            text-align: center;
        }
        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }
        @keyframes pulse {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
            100% {
                transform: scale(1);
            }
        }
        .pulse {
            animation: pulse 1.5s infinite;
        }
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .fade-in {
            animation: fadeIn 0.5s ease forwards;
        }
        /* 新增：图片查看器样式 */
        .image-viewer {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            z-index: 3000;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .image-viewer.active {
            opacity: 1;
            visibility: visible;
        }
        .viewer-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .viewer-image {
            max-width: 100%;
            max-height: 80vh;
            object-fit: contain;
            border: 5px solid white;
            border-radius: 5px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
        }
        .viewer-close {
            position: absolute;
            top: -40px;
            right: -40px;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            font-size: 1.5rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        .viewer-close:hover {
            background: rgba(0, 0, 0, 0.8);
        }
        .viewer-nav {
            position: absolute;
            top: 50%;
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding: 0 20px;
            transform: translateY(-50%);
        }
        .viewer-btn {
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            font-size: 1.5rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        .viewer-btn:hover {
            background: rgba(0, 0, 0, 0.8);
        }
        .viewer-info {
            position: absolute;
            bottom: -40px;
            left: 0;
            right: 0;
            color: white;
            text-align: center;
            font-size: 1rem;
        }
        @media (max-width: 768px) {
            .participants-grid {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            }
            .participant-imgs-container {
                height: 140px;
            }
            .header h1 {
                font-size: 2rem;
            }
            .draw-btn, .participants-toggle {
                padding: 0.7rem 1.5rem;
                font-size: 1.1rem;
            }
            .participant-management {
                flex-direction: column;
                align-items: center;
            }
            .form-actions {
                flex-direction: column;
            }
            .modal-content {
                padding: 1.5rem;
                margin: 0 1rem;
            }
            .preview-item {
                width: 70px;
                height: 70px;
            }
            /* 图片查看器响应式调整 */
            .viewer-nav {
                padding: 0 10px;
            }
            .viewer-btn {
                width: 40px;
                height: 40px;
                font-size: 1rem;
            }
            .viewer-close {
                top: 10px;
                right: 10px;
            }
            .viewer-info {
                bottom: 10px;
            }
        }
        @media (max-width: 480px) {
            .participants-grid {
                grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
                gap: 1rem;
            }
            .participant-imgs-container {
                height: 120px;
            }
            .participant-name {
                font-size: 0.9rem;
                padding: 0.8rem 0.5rem;
            }
            .winner-title {
                font-size: 1.5rem;
            }
            .winner-name {
                font-size: 1.5rem;
            }
            .winner-imgs-container {
                width: 160px;
                height: 160px;
            }
            .modal-title {
                font-size: 1.3rem;
            }
            .preview-item {
                width: 60px;
                height: 60px;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <h1>幸运大抽奖</h1>
    <p>点击下方按钮抽取幸运儿</p>
</div>
<button class="participants-toggle pulse" id="toggleParticipants">
    查看所有参与者
</button>
<!-- 参与者蒙版 -->
<div class="participants-overlay" id="participantsOverlay">
    <button class="close-participants" id="closeParticipants">×</button>
    <div class="participants-overlay-header">
        <h2>所有参与者</h2>
        <p id="participantsCount">共 0 位参与者</p>
    </div>
    <!-- 添加参与者管理按钮 -->
    <div class="participant-management">
        <button class="manage-btn" id="showAddModal">添加参与者</button>
        <button class="manage-btn" id="refreshParticipants">刷新列表</button>
    </div>
    <!-- 参与者添加弹框 -->
    <div class="participant-modal" id="addParticipantModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加新参与者</h3>
                <button class="close-modal" id="closeModal">×</button>
            </div>
            <form id="addParticipantForm">
                <div class="form-group">
                    <label for="participantName">姓名 <span style="color:red">*</span></label>
                    <input type="text" id="participantName" class="form-control" placeholder="输入参与者姓名" required>
                </div>
                <div class="form-group">
                    <label for="participantImages">上传图片（支持多张）</label>
                    <input type="file" id="participantImages" class="form-control" accept="image/*" multiple>
                    <p class="upload-hint">支持JPG、PNG、GIF格式，单张图片不超过5MB</p>
                    <!-- 图片预览区 -->
                    <div class="upload-preview" id="uploadPreview"></div>
                </div>
                <div class="form-actions">
                    <button type="submit" id="submitParticipant" class="draw-btn" style="flex: 1;">添加</button>
                    <button type="button" id="cancelAdd" class="draw-btn" style="flex: 1; background: #6c757d;">取消
                    </button>
                </div>
            </form>
        </div>
    </div>
    <div class="loading-indicator" id="loadingIndicator">正在加载参与者数据...</div>
    <div class="empty-state" id="emptyState">暂无参与者数据</div>
    <div class="participants-grid" id="participantsGrid">
        <!-- 参与者卡片将通过JavaScript动态生成 -->
    </div>
</div>
<!-- 新增：图片查看器 -->
<div class="image-viewer" id="imageViewer">
    <div class="viewer-content">
        <img src="" alt="参与者图片" class="viewer-image" id="viewerImage">
        <button class="viewer-close" id="viewerClose">×</button>
        <div class="viewer-nav">
            <button class="viewer-btn" id="viewerPrev">←</button>
            <button class="viewer-btn" id="viewerNext">→</button>
        </div>
        <div class="viewer-info" id="viewerInfo">1/1</div>
    </div>
</div>
<button class="draw-btn pulse" id="drawButton">开始抽奖</button>
<div class="result-container" id="resultContainer">
    <!-- 结果将通过JavaScript动态生成 -->
</div>
<!-- 抽奖动画 -->
<div class="draw-animation" id="drawAnimation">
    <div class="draw-spinner"></div>
    <div class="draw-message" id="drawMessage">正在抽取幸运儿...</div>
</div>
<script>
    // 全局存储上传的图片文件列表
    let uploadedImages = [];
    // 全局存储当前查看的图片数据
    let currentViewerImages = [];
    let currentViewerIndex = 0;
    let currentViewerName = '';

    // 获取参与者数据的函数
    function fetchParticipants() {
        return fetch('/list')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (!Array.isArray(data)) {
                    throw new Error('返回的数据格式不正确');
                }
                return data;
            });
    }
    // 执行抽奖的函数
    function performDraw() {
        return fetch('/begin', {
            headers: {
                'Accept': 'application/json'
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('抽奖请求失败');
                }
                const contentType = response.headers.get('content-type');
                if (contentType && contentType.includes('application/json')) {
                    return response.json();
                } else {
                    // 如果不是JSON响应，尝试解析HTML
                    return response.text().then(html => {
                        // 创建一个临时DOM解析HTML
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, 'text/html');
                        // 尝试查找中奖者信息
                        const winnerElement = doc.querySelector('.winner-name');
                        const winnerImgElement = doc.querySelector('.winner-img');
                        if (winnerElement) {
                            return {
                                name: winnerElement.textContent,
                                imgurl: winnerImgElement ? winnerImgElement.src : ''
                            };
                        } else {
                            throw new Error('未找到中奖者信息');
                        }
                    });
                }
            });
    }
    // 生成参与者卡片
    function generateParticipantCards(participants) {
        const grid = document.getElementById('participantsGrid');
        grid.innerHTML = '';
        if (participants.length === 0) {
            document.getElementById('emptyState').style.display = 'block';
            return;
        }
        document.getElementById('emptyState').style.display = 'none';
        participants.forEach((participant, index) => {
            const id = `participant-${index}`;
            // 处理图片路径
            let images = [];
            if (participant.imgurl) {
                const imgList = participant.imgurl.split(',');
                images = imgList.map(img =>
                    `{{ url_for('static', filename='img/') }}${img.trim()}`
                );
            } else {
                images = ['{{ url_for('static', filename='img/default-user.png') }}'];
            }
            const card = document.createElement('div');
            card.className = 'participant-card fade-in';
            card.style.animationDelay = `${index * 0.05}s`;
            // 存储图片数据到卡片元素上，方便点击查看
            card.setAttribute('data-name', participant.name);
            card.setAttribute('data-images', JSON.stringify(images));

            card.innerHTML = `
                    <button class="delete-btn" data-name="${participant.name}">×</button>
                    <div class="participant-imgs-container">
                        <div class="participant-imgs" id="${id}">
                            ${images.map(img =>
                `<img class="participant-img" src="${img}" alt="${participant.name}">`
            ).join('')}
                        </div>
                        ${images.length > 1 ? `
                        <div class="slider-dots">
                            ${images.map((_, i) =>
                `<div class="slider-dot ${i === 0 ? 'active' : ''}"
                                      data-slide="${i}"
                                      data-target="${id}"></div>`
            ).join('')}
                        </div>` : ''}
                    </div>
                    <div class="participant-name">${participant.name}</div>
                `;
            grid.appendChild(card);

            // 添加点击事件 - 查看所有图片
            card.addEventListener('click', function(e) {
                // 避免点击删除按钮时触发图片查看
                if (e.target.classList.contains('delete-btn')) {
                    return;
                }

                const name = this.getAttribute('data-name');
                const images = JSON.parse(this.getAttribute('data-images'));

                // 显示图片查看器
                showImageViewer(images, name);
            });
        });
        return participants.length;
    }

    // 显示图片查看器
    function showImageViewer(images, name) {
        currentViewerImages = images;
        currentViewerName = name;
        currentViewerIndex = 0;

        const viewer = document.getElementById('imageViewer');
        const viewerImg = document.getElementById('viewerImage');
        const viewerInfo = document.getElementById('viewerInfo');

        // 更新图片和信息
        viewerImg.src = currentViewerImages[currentViewerIndex];
        viewerInfo.textContent = `${currentViewerIndex + 1}/${currentViewerImages.length} - ${currentViewerName}`;

        // 显示查看器
        viewer.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    // 切换到下一张图片
    function showNextImage() {
        if (currentViewerImages.length <= 1) return;

        currentViewerIndex = (currentViewerIndex + 1) % currentViewerImages.length;
        updateViewerImage();
    }

    // 切换到上一张图片
    function showPrevImage() {
        if (currentViewerImages.length <= 1) return;

        currentViewerIndex = (currentViewerIndex - 1 + currentViewerImages.length) % currentViewerImages.length;
        updateViewerImage();
    }

    // 更新查看器中的图片
    function updateViewerImage() {
        const viewerImg = document.getElementById('viewerImage');
        const viewerInfo = document.getElementById('viewerInfo');

        viewerImg.src = currentViewerImages[currentViewerIndex];
        viewerInfo.textContent = `${currentViewerIndex + 1}/${currentViewerImages.length} - ${currentViewerName}`;
    }

    // 关闭图片查看器
    function closeImageViewer() {
        const viewer = document.getElementById('imageViewer');
        viewer.classList.remove('active');
        document.body.style.overflow = '';
    }

    // 初始化轮播
    function initSlider(slider, dots) {
        const images = slider.querySelectorAll('img');
        if (images.length <= 1) return null;
        let currentIndex = 0;
        let interval;
        let isTransitioning = false;
        const totalImages = images.length;
        slider.style.transform = 'translateX(0)';

        function slideTo(index) {
            if (isTransitioning) return;
            if (index < 0 || index >= totalImages) return;
            isTransitioning = true;
            currentIndex = index;
            slider.style.transition = 'transform 0.5s ease';
            slider.style.transform = `translateX(-${currentIndex * 100}%)`;
            if (dots) {
                dots.forEach(dot => dot.classList.remove('active'));
                dots[currentIndex].classList.add('active');
            }
        }

        function startAutoSlide() {
            interval = setInterval(() => {
                const nextIndex = (currentIndex + 1) % totalImages;
                slideTo(nextIndex);
            }, 3000);
        }

        slider.addEventListener('transitionend', () => {
            isTransitioning = false;
        });

        startAutoSlide();

        return {
            pause: () => clearInterval(interval),
            resume: startAutoSlide,
            slideTo: (index) => {
                clearInterval(interval);
                slideTo(index);
                startAutoSlide();
            }
        };
    }

    // 初始化所有轮播
    function initImageSliders() {
        document.querySelectorAll('.participant-imgs-container').forEach(container => {
            const slider = container.querySelector('.participant-imgs');
            const dots = container.querySelectorAll('.slider-dot');
            const sliderControl = initSlider(slider, dots);
            if (sliderControl) {
                container.addEventListener('mouseenter', sliderControl.pause);
                container.addEventListener('mouseleave', sliderControl.resume);
                if (dots) {
                    dots.forEach((dot, index) => {
                        dot.addEventListener('click', () => {
                            sliderControl.slideTo(index);
                        });
                    });
                }
            }
        });

        const winnerContainer = document.querySelector('.winner-imgs-container');
        if (winnerContainer) {
            const slider = winnerContainer.querySelector('.winner-imgs');
            const dots = winnerContainer.querySelectorAll('.slider-dot');
            const sliderControl = initSlider(slider, dots);
            if (sliderControl) {
                winnerContainer.addEventListener('mouseenter', sliderControl.pause);
                winnerContainer.addEventListener('mouseleave', sliderControl.resume);
                if (dots) {
                    dots.forEach((dot, index) => {
                        dot.addEventListener('click', () => {
                            sliderControl.slideTo(index);
                        });
                    });
                }
            }
        }
    }

    // 显示中奖者
    function showWinner(user) {
        const resultContainer = document.getElementById('resultContainer');
        resultContainer.innerHTML = '';
        if (!user) return;

        // 处理图片路径
        let images = [];
        if (user.imgurl) {
            // 如果imgurl是一个数组形式路径（来自JSON响应）
            if (Array.isArray(user.imgurl)) {
                images = user.imgurl;
            }
            // 如果imgurl是以逗号分隔的字符串（来自HTML解析）
            else if (typeof user.imgurl === 'string') {
                images = user.imgurl.split(',').map(img =>
                    `{{ url_for('static', filename='img/') }}${img.trim()}`
                );
            }
        } else {
            images = ['{{ url_for('static', filename='img/default-user.png') }}'];
        }

        const winnerCard = document.createElement('div');
        winnerCard.className = 'winner-card fade-in';
        winnerCard.innerHTML = `
                <h2 class="winner-title">恭喜中奖者</h2>
                <div class="winner-imgs-container">
                    <div class="winner-imgs" id="winner-imgs">
                        ${images.map(img =>
            `<img class="winner-img" src="${img}" alt="${user.name}">`
        ).join('')}
                    </div>
                    ${images.length > 1 ? `
                    <div class="slider-dots">
                        ${images.map((_, i) =>
            `<div class="slider-dot ${i === 0 ? 'active' : ''}"
                                  data-slide="${i}"
                                  data-target="winner-imgs"></div>`
        ).join('')}
                    </div>` : ''}
                </div>
                <div class="winner-name">${user.name}</div>
            `;
        resultContainer.appendChild(winnerCard);
        resultContainer.classList.add('show');

        // 滚动到结果区域
        setTimeout(() => {
            resultContainer.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        }, 500);

        // 初始化中奖者轮播
        setTimeout(initImageSliders, 100);
    }

    // 图片上传预览处理
    function initImageUpload() {
        const fileInput = document.getElementById('participantImages');
        const previewContainer = document.getElementById('uploadPreview');

        // 监听文件选择变化
        fileInput.addEventListener('change', function (e) {
            const files = e.target.files;
            if (!files || files.length === 0) return;

            // 清空已选文件（避免重复添加）
            uploadedImages = [];
            previewContainer.innerHTML = '';

            // 处理每个选中的文件
            Array.from(files).forEach(file => {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    alert(`"${file.name}" 不是图片文件，请重新选择`);
                    return;
                }

                // 验证文件大小（10MB以内）
                const maxSize = 10 * 1024 * 1024; // 10MB
                if (file.size > maxSize) {
                    alert(`"${file.name}" 超过10MB，请选择更小的图片`);
                    return;
                }

                // 存储文件到全局数组
                uploadedImages.push(file);

                // 创建预览元素
                const previewItem = document.createElement('div');
                previewItem.className = 'preview-item';

                const previewImg = document.createElement('img');
                previewImg.className = 'preview-img';
                previewImg.alt = '预览图';

                // 使用FileReader显示预览图
                const reader = new FileReader();
                reader.onload = function (event) {
                    previewImg.src = event.target.result;
                };
                reader.readAsDataURL(file);

                // 创建删除按钮
                const removeBtn = document.createElement('button');
                removeBtn.className = 'remove-img';
                removeBtn.innerHTML = '×';
                removeBtn.addEventListener('click', function () {
                    // 从全局数组中移除当前文件
                    const index = uploadedImages.findIndex(item => item.name === file.name);
                    if (index !== -1) {
                        uploadedImages.splice(index, 1);
                    }

                    // 移除预览元素
                    previewItem.remove();

                    // 重置fileInput（避免重复选择同一文件时不触发change事件）
                    fileInput.value = '';
                });

                previewItem.appendChild(previewImg);
                previewItem.appendChild(removeBtn);
                previewContainer.appendChild(previewItem);
            });
        });
    }

    // 添加参与者函数（支持FormData上传文件）
    function addParticipant(name, files) {
        // 创建FormData对象（用于文件上传）
        const formData = new FormData();
        formData.append('name', name);

        // 统一使用images[]作为键名，不添加索引
        files.forEach(file => {
            formData.append('images[]', file);
        });

        return fetch('/add', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message)
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    return data;
                } else {
                    throw new Error(data.message);
                }
            });
    }

    // 删除参与者
    function removeParticipant(name) {
        return fetch(`/remove/${encodeURIComponent(name)}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message)
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    return data;
                } else {
                    throw new Error(data.message);
                }
            });
    }

    // 初始化参与者弹框
    function initParticipantsOverlay() {
        const toggleBtn = document.getElementById('toggleParticipants');
        const closeBtn = document.getElementById('closeParticipants');
        const overlay = document.getElementById('participantsOverlay');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const participantsGrid = document.getElementById('participantsGrid');
        const participantsCount = document.getElementById('participantsCount');
        const emptyState = document.getElementById('emptyState');
        const showModalBtn = document.getElementById('showAddModal');
        const refreshBtn = document.getElementById('refreshParticipants');
        const addModal = document.getElementById('addParticipantModal');
        const closeModalBtn = document.getElementById('closeModal');
        const cancelAddBtn = document.getElementById('cancelAdd');
        const addForm = document.getElementById('addParticipantForm');
        const nameInput = document.getElementById('participantName');
        const previewContainer = document.getElementById('uploadPreview');

        // 初始化图片上传功能
        initImageUpload();

        // 刷新参与者列表
        function refreshParticipantsList() {
            // 显示加载指示器
            loadingIndicator.style.display = 'block';
            participantsGrid.innerHTML = '';
            emptyState.style.display = 'none';

            // 隐藏弹框
            addModal.classList.remove('active');

            // 获取最新的参与者数据
            fetchParticipants()
                .then(participants => {
                    // 生成卡片
                    const count = generateParticipantCards(participants);
                    participantsCount.textContent = `共 ${count} 位参与者`;

                    // 隐藏加载指示器
                    loadingIndicator.style.display = 'none';

                    // 初始化轮播
                    setTimeout(initImageSliders, 100);

                    // 添加删除按钮事件
                    document.querySelectorAll('.delete-btn').forEach(btn => {
                        btn.addEventListener('click', function (e) {
                            e.stopPropagation(); // 阻止事件冒泡到卡片
                            const name = this.getAttribute('data-name');
                            if (confirm(`确定要删除参与者 "${name}" 吗？`)) {
                                removeParticipant(name)
                                    .then(() => {
                                        refreshParticipantsList();
                                    })
                                    .catch(error => {
                                        alert(`删除失败: ${error.message}`);
                                    });
                            }
                        });
                    });
                })
                .catch(error => {
                    console.error('获取参与者数据失败:', error);
                    loadingIndicator.style.display = 'none';
                    emptyState.textContent = '加载失败，请重试';
                    emptyState.style.display = 'block';
                });
        }

        // 显示弹框
        showModalBtn.addEventListener('click', () => {
            addModal.classList.add('active');
            // 重置表单
            addForm.reset();
            uploadedImages = [];
            previewContainer.innerHTML = '';
        });

        // 关闭弹框（多种关闭方式）
        function closeModal() {
            addModal.classList.remove('active');
            // 重置表单
            addForm.reset();
            uploadedImages = [];
            previewContainer.innerHTML = '';
        }

        closeModalBtn.addEventListener('click', closeModal);
        cancelAddBtn.addEventListener('click', closeModal);

        // 点击弹框外部关闭
        addModal.addEventListener('click', (e) => {
            if (e.target === addModal) {
                closeModal();
            }
        });

        // 提交新参与者（表单提交事件）
        addForm.addEventListener('submit', function (e) {
            e.preventDefault(); // 阻止表单默认提交

            const name = nameInput.value.trim();
            if (!name) {
                alert('请输入参与者姓名');
                return;
            }

            // 调用添加参与者函数（传入姓名和文件列表）
            addParticipant(name, uploadedImages)
                .then(() => {
                    closeModal(); // 关闭弹框
                    refreshParticipantsList(); // 刷新列表
                })
                .catch(error => {
                    alert(`添加失败: ${error.message}`);
                });
        });

        // 刷新按钮事件
        refreshBtn.addEventListener('click', refreshParticipantsList);

        // 显示参与者蒙版
        toggleBtn.addEventListener('click', () => {
            overlay.classList.add('active');
            document.body.style.overflow = 'hidden';
            refreshParticipantsList();
        });

        // 关闭参与者蒙版
        closeBtn.addEventListener('click', () => {
            overlay.classList.remove('active');
            document.body.style.overflow = '';
            closeModal(); // 同时关闭弹框
        });

        // 点击蒙版空白处关闭
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                overlay.classList.remove('active');
                document.body.style.overflow = '';
                closeModal(); // 同时关闭弹框
            }
        });
    }

    // 初始化抽奖按钮
    function initDrawButton() {
        const drawButton = document.getElementById('drawButton');
        const drawAnimation = document.getElementById('drawAnimation');
        const drawMessage = document.getElementById('drawMessage');

        drawButton.addEventListener('click', () => {
            // 显示抽奖动画
            drawAnimation.classList.add('active');
            drawButton.textContent = '抽奖中...';
            drawButton.disabled = true;

            // 显示随机提示消息
            const messages = [
                "正在抽取幸运儿...",
                "分析参与者数据...",
                "准备奖品...",
                "随机数生成中...",
                "好运即将降临..."
            ];
            let messageIndex = 0;
            const messageInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                drawMessage.textContent = messages[messageIndex];
            }, 2000);

            // 执行抽奖
            performDraw()
                .then(user => {
                    // 隐藏抽奖动画
                    setTimeout(() => {
                        drawAnimation.classList.remove('active');
                        clearInterval(messageInterval);

                        // 显示中奖者
                        showWinner(user);

                        // 重置按钮状态
                        setTimeout(() => {
                            drawButton.textContent = '开始抽奖';
                            drawButton.disabled = false;
                        }, 2000);
                    }, 1500); // 保持动画显示一段时间
                })
                .catch(error => {
                    console.error('抽奖失败:', error);
                    drawAnimation.classList.remove('active');
                    clearInterval(messageInterval);

                    // 显示错误信息
                    setTimeout(() => {
                        alert('抽奖失败：' + error.message);
                        drawButton.textContent = '开始抽奖';
                        drawButton.disabled = false;
                    }, 500);
                });
        });
    }

    // 初始化图片查看器事件
    function initImageViewer() {
        const viewer = document.getElementById('imageViewer');
        const closeBtn = document.getElementById('viewerClose');
        const prevBtn = document.getElementById('viewerPrev');
        const nextBtn = document.getElementById('viewerNext');

        // 关闭查看器
        closeBtn.addEventListener('click', closeImageViewer);

        // 点击查看器外部关闭
        viewer.addEventListener('click', (e) => {
            if (e.target === viewer) {
                closeImageViewer();
            }
        });

        // 下一张图片
        nextBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            showNextImage();
        });

        // 上一张图片
        prevBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            showPrevImage();
        });

        // 键盘导航
        document.addEventListener('keydown', (e) => {
            if (!viewer.classList.contains('active')) return;

            if (e.key === 'ArrowRight') {
                showNextImage();
            } else if (e.key === 'ArrowLeft') {
                showPrevImage();
            } else if (e.key === 'Escape') {
                closeImageViewer();
            }
        });
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function () {
        initParticipantsOverlay();
        initDrawButton();
        initImageViewer(); // 初始化图片查看器

        // 如果有中奖者数据，显示中奖者
        // {% if user %}
        //     showWinner({
        //         name: "{{ user.name }}",
        //         imgurl: "{{ user.imgurl }}"
        //     });
        // {% endif %}
    });
</script>
</body>
</html>